package cn.hy.tiny.demo.core;

import com.mysql.jdbc.StringUtils;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

/**
 * @Author huang.xy
 * @Description TODO
 */
public class XMLMapperBuilder {
    private  final Configuration configuration;


    public XMLMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public void parseMapperStatement(InputStream inputStream) throws Exception {

        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();
        String namespace = rootElement.attributeValue("namespace");

        List<Element> selectElements = rootElement.selectNodes("//select");

        for (Element selectElement : selectElements) {
            MapperStatement mapperStatement = new MapperStatement();
            String id = selectElement.attributeValue("id");
            String paramType = selectElement.attributeValue("paramType");
            String resultType = selectElement.attributeValue("resultType");

            String namespaceId =  namespace +"."+ id;
            mapperStatement.setId(namespaceId);
            mapperStatement.setParamType(resolveClass(paramType));
            mapperStatement.setResultType(resolveClass(resultType));
            String sql = selectElement.getTextTrim();
            mapperStatement.setSql(sql);

            configuration.getMapperStatementCache().put(namespaceId,mapperStatement);
        }
    }

    private Class<?> resolveClass(String classStr) throws Exception {
        if (StringUtils.isNullOrEmpty(classStr)) return null;
        return Class.forName(classStr);

    }
}
